package com.csxh.util;

import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.PropertyUtils;

public class ServletUtil {

	// 获取请求的参数，并指定默认值
	@SuppressWarnings("unchecked")
	public static <T> T getParameter(String key, ServletRequest request, T defaultValue) {
		String str = request.getParameter(key);
		return StringUtil.toObjectfrom(str, defaultValue);
	}

	// 获取全局上下文的初始化参数，并指定默认值
	public static String getParameter(String key, ServletContext context, String defaultValue) {
		String value = context.getInitParameter(key);
		return null == value ? defaultValue : value;
	}

	// 获取请求的属性，并指定默认值
	@SuppressWarnings("unchecked")
	public static <T> T getAttribute(String key, ServletRequest request, T defaultValue) {
		Object value = request.getAttribute(key);
		return null == value ? defaultValue : (T) value;
	}

	// 获取全局上下文的属性，并指定默认值
	public static <T> T getAttribute(String key, ServletContext context, T defaultValue) {
		Object value = context.getAttribute(key);
		return null == value ? defaultValue : (T) value;
	}

	// 请求重定向并转发到指定另一个请求
	public static void redirect(HttpServletRequest request, HttpServletResponse response, String url, String returnUrl)
			throws IOException {
		// 将本次请求的相关数据保存到一个地方（全局上下文）
		request.getServletContext().setAttribute(Key.returnUrl, returnUrl);
		// 要求IE重新发一个请求
		response.sendRedirect(url);
	}

	// 转发到重定向之前设置的请求
	public static void forwardReturnUrl(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 判断上下文有没有设置重定向之前设置的请求
		Object returnUrl = request.getServletContext().getAttribute(Key.returnUrl);
		if (null != returnUrl) {
			request.getRequestDispatcher(returnUrl.toString()).forward(request, response);
		}
	}

	// 将请求参数自动转换成javabean的属性
	
	@SuppressWarnings("unchecked")
	public static<T> T paraseToJavaBean(HttpServletRequest request, Class<T> javabeanClassName) {
		// 通过反射创建javabean对象
		Object bean = null;
		try {
			//首先判断是否为序列化对象参数
			String str=request.getParameter(javabeanClassName.getSimpleName());
			if (null!=str) {
				return (T)StringUtil.unseriToObjectFrom(str);
			}

			
			bean =javabeanClassName.newInstance();
			Map<String, Object> propMap = PropertyUtils.describe(bean);
			
			Set<String> propSet = propMap.keySet();
			// 获取所有的请求参数
			Map<String, String[]> map = request.getParameterMap();

			for (Map.Entry<String, String[]> entry : map.entrySet()) {
				// 判断参数的名称是否为javabean的属性名
				String name = entry.getKey();
				if (!propSet.contains(name) || null==entry.getValue()) {
					continue;
				}

				String[] values = entry.getValue();
				Object[] vals = new Object[values.length];
				for (int i = 0; i < values.length; i++) {

					// 对values[0]进行编码转换
					byte[] bs = values[i].getBytes("iso-8859-1");
					values[i] = new String(bs, request.getServletContext().getInitParameter(Key.encoding));

					// 判断name对应是什么类型
					Object val = values[i];

					PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(bean, name);

					val = StringUtil.toObjectfrom(values[i], pd.getPropertyType());
					vals[i] = val;

				}

				if (vals.length==1) {					
					PropertyUtils.setProperty(bean, name, vals[0]);
				}else{
					PropertyUtils.setProperty(bean, name, vals);					
				}
			}

		} catch (Exception e) {
		}

		return (T)bean;

	}

	// 将来源地址保存到上下文中
	public static String setReferer(HttpServletRequest request) {

		String url = request.getHeader("referer");

		request.setAttribute(Key.returnUrl, url);

		return url;

	}

	public static void setJavaBean(HttpServletRequest request, Object bean) {
		request.setAttribute(Key.javaBean, bean);
	}

	public static void setUserBean(HttpServletRequest request, Object user) {
		request.setAttribute(Key.userBean, user);
	}

}
